﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using System.Text;
using System.IO;
using Gift.DAL;
using Gift.Model;
using Gift.Model.ENUM;
using Gift.WebApp;

namespace WebSite.admin.order
{
    public partial class orderCardList : BaseAdmin
    {

        public StringBuilder SelectCardType = new StringBuilder();
        public StringBuilder SelectCardPublishCompnay = new StringBuilder();
        protected string kw = "";
        protected int ot = 1;
        protected int pageCount = 0;
        protected string pid = "";
        protected int pageIndex = 1;
        protected int pageSize = 20;
        protected string order = "ordertime";
        protected PageList pl = new PageList();
        protected int t = 0;
        protected int total = 0;

        bool _isEdit = false;
        string _addDisplay = "none";

        public string AddDisplay
        {
            get { return _addDisplay; }
        }


        void BindCardType()
        {
            DataSet dsCardType = BaseFactory.theCardType.GetList("1=1");
            if (dsCardType != null && dsCardType.Tables.Count > 0)
            {
                foreach (DataRow dr in dsCardType.Tables[0].Rows)
                {
                    SelectCardType.AppendFormat("  <option value=\"{1}\">{0}</option>"
                                                , dr["name"].ToString()
                                                , dr["id"].ToString()
                                                );
                }
            }
        }


  

        private void OrderCardBind()
        {
            try
            {
                if (base.Request.QueryString["p"] != null)
                {
                    this.pageIndex = int.Parse(base.Request.QueryString["p"]);
                }
                if (base.Request.QueryString["ps"] != null)
                {
                    this.pageSize = Convert.ToInt32(base.Request.QueryString["ps"]);
                }
                if (base.Request.QueryString["or"] != null)
                {
                    this.order = base.Request.QueryString["or"];
                }
                if (base.Request.QueryString["ot"] != null)
                {
                    this.ot = Convert.ToInt32(base.Request.QueryString["ot"]);
                }
                if (base.Request.QueryString["pid"] != null)
                {
                    this.pid = base.Request.QueryString["pid"];
                }
                this.pl.TblName = "tbCardOrder";
                this.pl.StrGetFields = " *,(select payname from tbPay where pay = tbCardOrder.pay) as payName, (select isnull(sum(ProdPrice*prodnumber),0) from tbCar where orderid=tbCardOrder.orderid)  as sumprice   ";
                this.pl.FldName = this.order;
                this.pl.PageSize = this.pageSize;
                this.pl.PageIndex = this.pageIndex;
                this.pl.DoCount = 1;
                this.pl.OrderType = this.ot;
                this.pl.StrWhere = "1=1 " + GetSqlWhere();

                this.total = Convert.ToInt32(BaseFactory.thePageList.GetPageList(this.pl).Rows[0]["Total"]);
                this.pl.DoCount = 0;
                DataTable pageList = BaseFactory.thePageList.GetPageList(this.pl);
                new PageListNo().DelPageSize(pageList, this.total);
                this.rptOrder.DataSource = pageList.DefaultView;
                this.rptOrder.DataBind();
            }
            catch (Exception ex)
            {
            }
        }

 

        void BindCompanyList()
        {
            DataSet dsCompany = BaseFactory.theCompany.GetList(" LevelId = 1");
                if (dsCompany != null && dsCompany.Tables.Count > 0)
                {
                    foreach (DataRow dr in dsCompany.Tables[0].Rows)
                    {
                        if (dr["id"].ToString() == base.Administrator.CompanyId)
                        {
                            this.SelectCardPublishCompnay.AppendFormat("  <option selected=\"selected\" value=\"{1}\">{0}</option>"
                                                           , dr["name"].ToString()
                                                           , dr["id"].ToString()
                                                           );
                        }
                        else
                        {
                            this.SelectCardPublishCompnay.AppendFormat("  <option value=\"{1}\">{0}</option>"
                                                           , dr["name"].ToString()
                                                           , dr["id"].ToString()
                                                           );
                        }

                    }
                }
        }

        private string GetSqlWhere()
        {
            StringBuilder sbSql = new StringBuilder();
            sbSql.Append(" and pay = 15");
            if (! string.IsNullOrEmpty(Request.QueryString["kw"]))
            {
                this.kw = base.Request.QueryString["kw"].Trim();
                if (Request.QueryString["t"] == "goodsname")
                {
                    sbSql.Append(" and orderid in(select orderid from tbCar c join tbGoods s on c.productid = s.id  where s.goodsName like '%" + Request.QueryString["kw"] + "%') ");
                }
                else
                {
                    sbSql.AppendFormat(" and {0} like '%{1}%' "
                                        , Request.QueryString["t"]
                                        , Request.QueryString["kw"]
                                        );
                }
            }
            if (!string.IsNullOrEmpty(Request.QueryString["sd"]))
            {
                sbSql.Append(" and (sendDate >= '" + Request.QueryString["sd"] + "' or sendDate is null)");
            }
            if (!string.IsNullOrEmpty(Request.QueryString["ed"]))
            {
                sbSql.Append(" and (sendDate <= '" + Request.QueryString["ed"] + "' or sendDate is null)");
            }


            if (!string.IsNullOrEmpty(Request.QueryString["states"]))
            {
                sbSql.Append(" and states=" + Request.QueryString["states"] + " ");
            }
            else
            {
                sbSql.Append(" and states=0 ");
            }

            if (!string.IsNullOrEmpty(Request.QueryString["companyid"]))
            {
                tbCompany oCompany = BaseFactory.theCompany.GetModel(int.Parse(Request.QueryString["companyid"]));
                if (oCompany != null)
                {
                    sbSql.AppendFormat(" and orderid in (select oa.orderid from tbOrderAccount oa join tbCard{0} c on oa.cardId = c.CardId and c.CompanyId = {1}) "
                        , oCompany.CompanyCode
                        , Request.QueryString["companyid"] 
                         );
                }
            }
                 //--
            if (!string.IsNullOrEmpty(Request.QueryString["cardtype"]))
            {
                tbCardType oCardType = BaseFactory.theCardType.GetModel(int.Parse(Request.QueryString["cardtype"]));
                if (oCardType != null)
                {
                    tbProfessionAreaType oProfessionAreaType = BaseFactory.theProfessionAreaType.GetModel(oCardType.professionAreaTypeId);
                    if (oProfessionAreaType != null)
                    {
                        tbCompany oCompany = BaseFactory.theCompany.GetModel(oProfessionAreaType.CompanyId);
                        if (oCompany != null)
                        {
                            sbSql.AppendFormat(" and orderid in (select oa.orderid from tbOrderAccount oa join tbCard{0} c on oa.cardId = c.CardId and  c.CardTypeId = {1})" 
                                 , oCompany.CompanyCode           
                                 ,Request.QueryString["cardtype"]);
                        }
                    }
                }
               
            }

            if (sbSql.Length == 3) return string.Empty;
            else
            {
                return sbSql.ToString();
            }
        }


        private DataTable GetExportData()
        {
            string sql = "select distinct '' as 物流公司, '' as 物流单号,'' as 物流查询网址,'' as 物流查询电话,'' as 发货时间,订单号 as 寄件客户编码_订单编号,'' as 寄件人,'' as 寄件公司, "
                         + " '' as 寄件人联系电话,'' as 寄件人地址,商品名称,"
                         + " sum(prodNumber) as 数量,收货人,'' as 收货公司,收货人联系电话,收货地址, 备注,'' as 付款方式,'' as 保价,'\\' as 保价金额,"
                         + "'' as 代收货款,'\\' as 代收货款卡号, '' as 代收货款金额,'' as 备注1,'' as 备注2, '' as 备注3 "                          
                         + " from  "
                         + " ( "
                         + " select O.ordercode as 订单号,"
                         + " S.goodsName+'(' + convert(varchar(30),ge.salePrice) +')' as 商品名称,  O.cname1 as 收货人,isnull(O.tel1,'') + ';' + isnull(phone1,'') as 收货人联系电话, convert(varchar(10),O.senddate,111) as 送货日期, address1 as 收货地址,SendCompany as 物流,SendCode as 物流单号,[content] as 备注 ,C.prodNumber "
                         + " from tbCardOrder O join tbCar C on O.orderid = C.orderid join tbGoods S on C.productid = S.Id "
                         + " join tbGoodsEntitys ge on s.id = ge.goods  where 1=1 ";
            sql = sql + GetSqlWhere()
                  + " ) a "
                  + " group by 订单号,收货人, 收货人联系电话,收货地址,商品名称 ,备注";
        
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            return table;
        }





        protected void btnUpdateStates_Click(object sender, EventArgs e)
        {
            try
            {
                string str = base.Request.Form["Item"];
                string sSql = string.Format(" update tbCardOrder set states={1} where orderid in ({0}); ", str,base.Request.Form["flag"]);
                SQLAccess.DoSql(sSql);

                base.Alert("更新成功！");
                this.OrderCardBind();
            }
            catch
            {
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
         
            if (!base.IsPostBack)
            {
                this.ValidateLoginUser();
                if (!base.GetValidateLoginRule(Gift.Model.ENUM.ERule.OrderCardEdit))
                {
                    this.btnUpdateStates.Visible = false;
                }
                this.btnUpdateStates.Attributes.Add("disabled", "disabled");
                if (base.Request.QueryString["t"] != null)
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "sa", "<script type=\"text/javascript\">selectIsExitItem(\"selectOrder\",\"" + base.Request.QueryString["t"] + "\");</script>");
                }
                if (base.Request.QueryString["ps"] != null)
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "sPs", "<script type=\"text/javascript\">selectIsExitItem(\"selectPageSize\",\"" + base.Request.QueryString["ps"] + "\");</script>");
                }
                if (base.Request.QueryString["states"] != null)
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "ss", "<script type=\"text/javascript\">selectIsExitItem(\"selectStates\",\"" + base.Request.QueryString["states"] + "\");</script>");
                }
                if (base.Request.QueryString["cardtype"] != null)
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "sct", "<script type=\"text/javascript\">selectIsExitItem(\"selectCardType\",\"" + base.Request.QueryString["cardtype"] + "\");</script>");
                }
                if (base.Request.QueryString["companyid"] != null)
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "scpc", "<script type=\"text/javascript\">selectIsExitItem(\"selectCardPublishCompnay\",\"" + base.Request.QueryString["companyid"] + "\");</script>");
                }

                this.BindCardType();
                this.BindCompanyList();
                this.OrderCardBind();
            }
        }




        protected void btnExport_Click(object sender, EventArgs e)
        {
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";//设置导出文件的名称   
            DataTable dt = GetExportData();
            ExcelHelper.ExportDataTableToExcel(dt, fileName, "订单列表");
        }

        private string BuildExportHTML(System.Data.DataTable dt)
        {
            string result = string.Empty;
            int readCnt = dt.Rows.Count;
            int colCount = dt.Columns.Count;

            int pagerecords = 5000;
            string strTitleRow = "";
            for (int j = 0; j < colCount; j++)
            {
                strTitleRow += dt.Columns[j].ColumnName + "\t";
            }
            strTitleRow += "\r\n";

            StringBuilder strRows = new StringBuilder();
            int cnt = 1;
            for (int i = 0; i < readCnt; i++)
            {
                //strRows.Append("");
                for (int j = 0; j < colCount; j++)
                {
                    if (dt.Columns[j].DataType.Name == "DateTime" || dt.Columns[j].DataType.Name == "SmallDateTime")
                    {
                        if (dt.Rows[i][j].ToString() != string.Empty)
                        {
                            strRows.Append(Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy年MM月dd日") + "\t");
                        }
                        else
                            strRows.Append("\t");
                    }
                    else
                    {
                        strRows.Append(dt.Rows[i][j].ToString().Trim() + "\t");
                    }
                }
                strRows.Append("\r\n");
                cnt++;
                if (cnt >= pagerecords)
                {
                    result += strRows.ToString();
                    strRows.Remove(0, strRows.Length);
                    cnt = 1;
                }
            }
            result = strTitleRow + result + strRows.ToString();
            return result;
        }





        protected void ibtnInport_Click(object sender, ImageClickEventArgs e)
        {

            if (this.FileUpload1.FileContent.Length <= 0)
            {
                Response.Write("<script>alert('请选择要导入的EXCEL文件！')</script>");
                return;
            }
            else
            {
                try
                {
                    string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
                    this.FileUpload1.SaveAs(Server.MapPath("../uploadTempFile/" + fileName));

                    DataTable dtResult = new DataTable();
                    dtResult = ExcelHelper.ImportDataTableFromExcel(Server.MapPath("../uploadTempFile/" + fileName),"订单列表",0);

                    DataRow[] dr = dtResult.Select();
                  
                    int rowsnum = dtResult.Rows.Count;
                    if (rowsnum == 0)
                    {
                        Response.Write("<script>alert('Excel表为空表,无数据！')</script>");
                        return;
                    }
                    int iInportSum = 0;
                    for (int i = 0; i < rowsnum; i++)
                    {
                        string orderCode = dr[i]["寄件客户编码_订单编号"].ToString();
                        string sendCompany = dr[i].Table.Columns.Contains("物流公司") ? dr[i]["物流公司"].ToString() : string.Empty;
                        string sendCode = dr[i].Table.Columns.Contains("物流单号") ? dr[i]["物流单号"].ToString() : string.Empty;
                        string sendUrl = dr[i].Table.Columns.Contains("物流查询网址") ? dr[i]["物流查询网址"].ToString() : string.Empty; 
                        string sendPerson = dr[i].Table.Columns.Contains("寄件人") ? dr[i]["寄件人"].ToString() : string.Empty; 
                        string sendPersonCompany = dr[i].Table.Columns.Contains("寄件公司") ? dr[i]["寄件公司"].ToString() : string.Empty; 
                        string sendPersonAddress = dr[i].Table.Columns.Contains("寄件人地址") ? dr[i]["寄件人地址"].ToString() : string.Empty;
                        string sendPersonTelephone = dr[i].Table.Columns.Contains("物流查询电话") ? dr[i]["物流查询电话"].ToString() : string.Empty;
                        string sendDate1 = DateTime.Now.ToString() ;
                        if (dr[i].Table.Columns.Contains("发货时间"))
                        {
                            try
                            {
                                sendDate1 = DateTime.Parse(dr[i]["发货时间"].ToString()).ToString();
                            }
                            catch
                            { }
                        }

                        //if (!string.IsNullOrEmpty(sendCode) )
                        //{
                            StringBuilder sbSql = new StringBuilder();
                            sbSql.AppendFormat("update tbCardOrder set SendCode='{0}',SendCompany='{1}', SendUrl='{2}',SendPerson='{3}',SendPersonCompany='{4}',sendPersonAddress='{5}',SendTelphone='{6}',senddate1='{8}' where ordercode = {7};"
                                 , sendCode
                                 , sendCompany
                                 , sendUrl
                                 , sendPerson
                                 , sendPersonCompany
                                 , sendPersonAddress
                                 ,sendPersonTelephone
                                 , orderCode
                                 ,sendDate1
                                 );
                            sbSql.Append("update tbCardOrder set states=2 where ordercode = '" + orderCode + "' and ( isnull(states,0)=0 or states=1)");
                            SQLAccess.DoSql(sbSql.ToString());
                            iInportSum++;
                    }
                    base.Alert("成功导入" + iInportSum.ToString() + "条用户信息！");
                    this.OrderCardBind();
                }
                catch (Exception ex)
                {
                    base.Alert("请检查Excel格式是否正确！");
                    this.OrderCardBind();
                }
            }
        }

     

        protected void ibtnExport0_Click(object sender, ImageClickEventArgs e)
        {
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";//设置导出文件的名称
         
            DataTable dt = GetExportDataForTemplate();
            ExcelHelper.ExportDataTableToExcel(dt, fileName, "订单列表");

        }

        private DataTable GetExportDataForTemplate()
        {
            string sql = "select top 0 '' as 订单号, "
                         + " '' as 送货日期,"
                         + " '' as 收件人,"
                         + " '' as 联系电话,"
                         + "'' as 送货地址,"
                         + " '' as 产品名称,"
                         + " '' as 数量,"
                         + " '' as 备注,"
                         + "'' as 物流,'' as 物流单号"
                         + " from DB_order O join DB_Car C on O.orderid = C.orderid join DB_Shoppro S on C.productid = S.proid";

            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            return table;
        }


        void ValidateLoginUser()
        {
            if (!base.GetValidateLoginRule(Gift.Model.ENUM.ERule.OrderCardList))
            {
                base.Response.Write("<script language=javascript>window.top.location.href='../login.aspx';</script>");
                base.Response.End();
            }
            if (base.GetValidateLoginRule(Gift.Model.ENUM.ERule.OrderCardAdd))
            {
                _addDisplay = "block";
            }
            if (base.GetValidateLoginRule(Gift.Model.ENUM.ERule.OrderCardEdit))
            {
                _isEdit = true;
            }
        }

        protected void rptOrder_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            base.SetListPerssion(e, _isEdit);

        }



    }
}